import axios from 'axios'
import IndexDB from "@/utils/IndexDB.ts";
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// 创建http实列
const $http = axios.create({
  baseURL: '/v1/api', // 请求路径
})

// 请求拦截
$http.interceptors.request.use(config => {
  config.headers = config.headers || {}
  if (localStorage.getItem('yunque-token')){
    config.headers.Authorization='Bearer '+localStorage.getItem('yunque-token')
  }
  return config
})

$http.interceptors.response.use(res => {
  return res.data
}, error => {
  if(error.response.status === 401){
    localStorage.clear()
    IndexDB.remove('yunque-user').then(() => {})
    location.href=('/login?redirect='+location.pathname)
  }
  return Promise.reject(error)
})
export default $http
